#include "ctestmodel.h"
#include "mainwindow.h"
#include "def.h"

CTestModel::CTestModel(QObject *parent) : QAbstractListModel(parent)
{
    test = new CTest;
    test->parseDomDocument(fileTest.newFile());
}

CTestModel::CTestModel(QString &path, QObject *parent) : QAbstractListModel(parent)
{
    test = new CTest;
    test->parseDomDocument(fileTest.loadT2PFile(path));
    generateTestList();
    //this->init(test->getListQuestion());
}

CTestModel::~CTestModel()
{
    if (test) delete test;
}

bool CTestModel::writeTestList(QString t2pFile)
{
    if (fileTest.saveFile(t2pFile, test->getDomDocument()))
	return true;
    return false;
}

CTest& CTestModel::getTest()
{
    return *test;
}

QString CTestModel::getTmpDir()
{
    return this->fileTest.getTmpPath();
}

void CTestModel::generateTestList()
{
    for (int i=0; i<test->getListQuestion().count();i++)
    {
        QVector<QString> testVector;
        testVector.append(tr("Вопрос №") + QVariant(i+1).toString());
        testVector.append(test->getListQuestion().getQuestion(i).getTextQuestion());
	testVector.append(test->getListQuestion().getQuestion(i).getComment());
        for (int j=0; j<test->getListQuestion().getQuestion(i).getListAnswer().count(); j++)
        {
            testVector.append(test->getListQuestion().getQuestion(i).getListAnswer().getAnswer(j).getTextAnswer());
            testVector.append(QVariant(test->getListQuestion().getQuestion(i).getListAnswer().getAnswer(j).isRightAnswer()).toString());
//            testVector.append(test->getListQuestion().getQuestion(i).getListAnswer().getAnswer(j).getComment());
        }
        testList.append(testVector);
    }
}

void CTestModel::addEmptyAnswer(const int &nQuestion, const int &count)
{
    if (nQuestion<testList.count())
    {
        for (int i=0; i<count; i++)
        {
	    testList[nQuestion].append(QString());//текст ответа
	    testList[nQuestion].append(QVariant(false).toString()); //верно/неверно
//            testList[nQuestion].append(QString());//текст коментария
        }
    }
}

QVariant CTestModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid())
	    return QVariant();
    if(index.row() > testList.count() || index.column() > columnCount(index))
	    return QVariant();
    if(role == Qt::DisplayRole)
    {
        return QVariant(testList.at(index.row()).at(index.column()));
    }
    else
        return QVariant();
}

QVariant CTestModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    Q_UNUSED(section);
    Q_UNUSED(orientation);
    Q_UNUSED(role);
    return QVariant();
}

int CTestModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return testList.count();
}
int CTestModel::columnCount(const QModelIndex &parent) const
{
//    //Почему-то 1 возвращать надо, если парент невалидный.
//    //Потом разберемся...
    if (!parent.isValid()) return 1;
//    //Выделен итем у listVew
    return testList[parent.row()].count();;
}

Qt::ItemFlags CTestModel::flags(const QModelIndex &index) const
{
    Q_UNUSED(index);
    return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

bool CTestModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(!index.isValid())
        return false;

    if(index.row() > testList.count() || index.column() > columnCount(index))
    {
        return false;
    }
    if(role == Qt::EditRole)
    {
        testList[index.row()][index.column()] = value.toString();
        QModelIndex ind = createIndex(index.row(), 0);
        emit dataChanged(ind, ind);
        //save to QListQuestion
	updateListQuestion(index.row());
        return true;
    }
    else
        return false;
}

bool CTestModel::removeColumns(int column, int count, const QModelIndex &parent)
{
    testList[parent.row()].remove(column, count);
    return true;
}

bool CTestModel::insertRow(int row, const QModelIndex &parent)
{
    Q_UNUSED(parent);
    if(row > testList.count())
	return false;
    //beginInsertRows(QModelIndex(), row, row);
    testList.insert(row, QVector<QString>(3));
    testList[row][0] = tr("Вопрос №") + QVariant(row+1).toString();
    CQuestion q;
    CListQuestion lq;
    q.setNew(true);
    lq = test->getListQuestion();
    lq.addQuestion(q);
    test->setListQuestion(lq);
    //endInsertRows();
    QModelIndex ind = createIndex(row,0);
    emit dataChanged(ind, ind);

    return true;
}

bool CTestModel::removeRow(int row, const QModelIndex &parent)
{
    Q_UNUSED(parent);
    if (row>=testList.count()) return false;
    this->testList.removeAt(row);
    QModelIndex ind = createIndex(row,0);
    CListQuestion lq;
    lq = test->getListQuestion();
    lq.delQuestion(row);
    test->setListQuestion(lq);
    test->removeChildFormDomDocument(row);
    for (int i=0; i<testList.count(); i++)
    {
	testList[i][0] = tr("Вопрос №") + QVariant(i+1).toString();
    }
    emit dataChanged(ind, ind);
    return true;
}

void CTestModel::updateListQuestion(int n)
{
    CListAnswer la;
    for(int i=0; i<(testList[n].count()-2)/ANSWCOLUMN; i++)
    {
	CAnswer answ;
	answ.setTextAnswer(testList[n].at(i*ANSWCOLUMN+3));//текст ответа
	answ.setRightAnswer(QVariant(testList[n].at(i*ANSWCOLUMN+4)).toBool());//верно/неверно
//	answ.setComment(testList[n].at(i*3+4));//коммент
	la.addAnswer(answ);
    }
    CListQuestion lq;
    lq = test->getListQuestion();
    CQuestion q;
    q.changed(true);
    q.setNew(lq[n].isNew());
    //q.setQuestionType(questionMulti);
    q.setTextQuestion(testList[n].at(1));//текст вопроса
    q.setComment(testList[n].at(2));//текст комента
    q.setListAnswer(la);
    lq[n] = q;//<--- !!!!!!!!!!!!!!!!
    test->setListQuestion(lq);
};

void CTestModel::savePrintSettings(CPrintSettings &printSettings)
{
    test->setPrintSettings(printSettings);
}

QString CTestModel::addImage(QString &path)
{
    return fileTest.addImage(path);
}
